package com.file;

import java.io.*;
import java.nio.charset.Charset;

/**
 * 测试文件的几种写的方式
 */
public class FileWriterTest {

    public static void main(String[] args) throws IOException {
        long l1 = System.currentTimeMillis();
//        fileWriterMethod();
//        bufferWriterMethod();
        fileOutPutStreamMethod();
        long l2 = System.currentTimeMillis();
        System.out.println(l2 - l1);
    }

    public static void fileWriterMethod() throws IOException {
        String data = "This content will append to the end of the file\n";
        File file = new File("/Users/momo/file.text");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(file, true);
        fileWriter.write(data);
        fileWriter.flush();
        fileWriter.close();
    }

    public static void bufferWriterMethod() throws IOException {
        String data = "This content will append to the end of the file\n";
        File file = new File("/Users/momo/file.text");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(data);
        bufferedWriter.flush();
        bufferedWriter.close();
        fileWriter.close();
    }

    public static void fileOutPutStreamMethod() throws IOException {
        String data = "This content will append to the end of the file\n";
        File file = new File("/Users/momo/file.text");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file, true);
        fileOutputStream.write(data.getBytes(Charset.defaultCharset()));
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}
